﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace StreetlightGames.XnaEngine
{
    public class KeyboardController : GameComponent
    {
        private KeyboardState _state;
        private KeyboardState _previousState;

        /// <summary>Gets the KeyMap value</summary>
        public List<KeyMapData> KeyMap
        {
            get { return _keyMap; }
        }
        private List<KeyMapData> _keyMap = new List<KeyMapData>();

        /// <summary>Gets the Buttons value</summary>
        public GamePadButtons Buttons
        {
            get { return _buttons; }
        }
        private GamePadButtons _buttons = new GamePadButtons();

        /// <summary>
        /// Creates a new instance.
        /// </summary>
        /// <param name="game">Game</param>
        public KeyboardController(Game game)
            : base(game)
        {
        }

        public override void Update(GameTime gameTime)
        {
            _state = Keyboard.GetState();

            Microsoft.Xna.Framework.Input.Buttons? buttons = null;

            foreach (KeyMapData data in _keyMap)
            {
                if (_state.IsKeyDown(data.Keys) && (!data.CanHoldButton || !_previousState.IsKeyDown(data.Keys)))
                {
                    if (buttons == null)
                    {
                        buttons = data.Buttons;
                    }
                    else
                    {
                        buttons |= data.Buttons;
                    }
                }
            }

            if (buttons.HasValue)
            {
                _buttons = new GamePadButtons(buttons.Value);
            }
            else
            {
                _buttons = new GamePadButtons();
            }
            
            base.Update(gameTime);

            _previousState = _state;
        }
    }
}
